from django.core.serializers.json import DjangoJSONEncoder
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view
from .models import CustomerInfo
from .serializers import CustomerInfoSerializer
from utils.exception_enum import StatusCodeEnum
from utils.commonException import BusinessException, APIException
from utils.response import R, json_response_success, json_response_error
import environ
import os
from django.core.cache import cache
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
env = environ.Env()
@api_view(['GET'])

def customer_list(request):
    """获取所有客户信息"""
    try:
        customers = CustomerInfo.objects.using('daijia_customer_db').filter(is_deleted=0)
        if not customers.exists():
            raise BusinessException(StatusCodeEnum.NODATA_ERR)
        serializer = CustomerInfoSerializer(customers, many=True)
        print(serializer.data)
        return JsonResponse(R.ok(serializer.data))
    except BusinessException as e:
        return JsonResponse(R.from_enum(e.enum_cls), status=400)
    except Exception as e:
        print(e)
        return JsonResponse(R.error(str(e), StatusCodeEnum.SERVER_ERR.code), status=500)


@api_view(['GET'])
def customer_detail(request, pk):
    """获取单个客户详情"""
    try:
        customer = CustomerInfo.objects.using('daijia_customer_db').get(pk=pk, is_deleted=0)
        serializer = CustomerInfoSerializer(customer)
        return JsonResponse(R.ok(serializer.data))
    except CustomerInfo.DoesNotExist:
        return JsonResponse(R.from_enum(StatusCodeEnum.NODATA_ERR), status=404)
    except Exception as e:
        return JsonResponse(R.error(str(e), StatusCodeEnum.SERVER_ERR.code), status=500)


# 测试试图
@api_view(['GET'])
def test(request):
    print(request.GET.get('id'))
    return     JsonResponse({"id": 'user.id', "name": 'user.name'},status=200,safe=False)
@api_view(['POST'])
def postTest(request):
    # 获取这个里面的所有的元素的话就直接通过这个方法进行这个获取就行了
    # for item in request.GET.items():
    #     print(item)
    # print(type(request.GET.get('ids')))
    # 通过这个就可以直接获取到这个url当中的所有的数据内容格式谢谢
    for e in request.GET.getlist("ids"):
        print(e)
    # print(request.POST.get('test'))
    # print(request.POST.get('dddd'))
    # 获取 POST 请求体 (JSON)
    # new_name = request.data.get('name')  # "Alice"
    # print(new_name)
    # request.
    return     JsonResponse({"id": 'user.id', "name": 'user.name'},status=200,safe=False)
from django.core.files.storage import FileSystemStorage
# 文件上传
@api_view(['POST'])
def upload_file(request):
    if request.method == 'POST' and request.FILES.get('file'):
        uploaded_file = request.FILES['file']

        # 保存文件到media目录
        fs = FileSystemStorage()
        filename = fs.save(uploaded_file.name, uploaded_file)
        file_url = fs.url(filename)

        return JsonResponse({
            'status': 'success',
            'message': '文件上传成功',
            'file_url': file_url
        })
    return JsonResponse({
        'status': 'error',
        'message': '请上传文件'
    }, status=400)